
# Create your views here.
import re
from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views import View
import logging

from django_redis import get_redis_connection

from carts.utils import merge_cart_cookie_to_redis
from meiduo_mall.utils.response_code import RETCODE
from qqlogin.models import QQUsers
from qqlogin.utils import generate_access_token, check_access_token
from users.models import User

logger = logging.getLogger('django')


class QQURLLogin(View):
    def get(self, request):
        next = request.GET.get('next')

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        login_url = oauth.get_qq_url()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'login_url': login_url})


class QQUsersView(View):
    def get(self, request):
        code = request.GET.get('code')

        if not code:
            return http.HttpResponseForbidden('缺少必要参数')

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,)
        try:
            access_token = oauth.get_access_token(code)

            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)

            return http.HttpResponseForbidden('认证失败')

        try:
            oauth_user = QQUsers.objects.get(openid=openid)

        except QQUsers.DoesNotExist:
            access_token = generate_access_token(openid)

            context = {'access_token': access_token}

            return render(request, 'oauth_callback.html', context)

        else:
            qq_user = oauth_user.user

            login(request, qq_user)

            response = redirect(reverse('center:index'))

            response.set_cookie('username', qq_user.username, max_age=3600 * 24 * 15)

            response = merge_cart_cookie_to_redis(request, response, qq_user)

            return response

    def post(self, request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        access_token = request.POST.get('access_token')

        if not all([mobile, password, sms_code_client]):
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match('^1[345789]\d{9}$', mobile):
            return http.HttpResponseForbidden('手机号格式不正确')

        if not re.match('^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码格式不正确')

        redis_conn = get_redis_connection('verify_code')

        sms_code_server = redis_conn.get(mobile)

        if sms_code_server is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '无效的短信验证码'})

        if sms_code_server.decode() != sms_code_client:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '输入短信验证码有误'})

        openid = check_access_token(access_token)

        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '无效的openid'})

        try:
            user = User.objects.get(mobile=mobile)
        except Exception:
            user = User.objects.create_user(username=mobile, password=password, mobile=mobile)
        else:
            if not user.check_password(password):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})

        try:
            QQUsers.objects.create(openid=openid, user=user)
        except Exception:
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'QQ登录失败'})

        login(request, user)

        next = request.GET.get('state')
        response = redirect(next)

        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        response = merge_cart_cookie_to_redis(request, response, user)

        return response